import React, { useState, useEffect, Suspense, useMemo, useCallback } from "react";
import { Switch, Route, Redirect, useLocation } from "react-router-dom";
import Loadings from './components/Loading/RouterLoading' ;
import HomeLoading from "./components/Loading/HomeLoading";
import Error from "./views/Error/Index";
import { connect } from "react-redux";
import axios from 'axios' ;
const Login = React.lazy(() => import("./views/Login/Index"));
const App = React.lazy(() => import("./views/Home/Index"));
// },1000 ));
let Router = ({ UpateUserInfo, getUserInfo, history }) => {
  const [loginIn, setLogin] = useState(false);
  const location = useLocation();
  const getToken = useCallback(async () => {
    let { data: res } = await axios.get("/ap/user");
    if (res.ok !== 0) {
      getUserInfo({ type: "getuser", data: res.data });
      getUserInfo({ type: "issystemon", flat: "1" });
  //     // getUserInfo({type:'getHistory',history:history})
    }
  }, []);
  useEffect(() => {
    // if(window.location.href.substring(window.location.origin.length,window.location.href.length) == '/') {
    //   window.location.href = window.location.origin + '/admin' ;
    //   console.log(window.location.origin + '/admin')
    // }
    getToken();
  }, []);
  return (
    <Suspense fallback={ location.pathname !== "/login" && location.pathname !== '/admin'? null: location.pathname == "/login"?<Loadings></Loadings> : <HomeLoading />}>
      <Switch>
        {/* 这样在Route里写重定向有效果  单独写初次有效果 刷新无效果 */}

        <Route path="/" exact render={() => <Redirect to="/admin" />}></Route>
        <Route path="/admin" exact component={App}></Route>
        <Route path="/login" exact component={Login}></Route>
        <Route
          exact
          render={() => {
            if (
              location.pathname !== "/login" &&
              location.pathname !== "/" &&
              location.pathname !== "/admin"
            ) {
              return <Error />;
            } else {
              return <Redirect to={location.pathname}></Redirect>;
            }
          }}
        ></Route>
        {/* <Redirect from='/' to="/admin"></Redirect> */}
      </Switch>
    </Suspense>
  );
};
export default connect(
  (state) => state,
  (dispatch) => {
    return {
      getUserInfo: (data) => dispatch(data),
    };
  }
)(Router);
